package com.woniu.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.woniu.outlet.elasticSearch.GoldESDao;
import com.woniu.outlet.elasticSearch.po.Gold;
import com.woniu.outlet.mysql.GoldMysqlMapper;
import com.woniu.outlet.mysql.po.GoldMysql;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import squall.http.HttpUtil;

import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

/**
 * @description:
 * @author: my
 * @time: 2021/4/22 9:55
 */
@Slf4j
@Component
public class GoldUtils {
    public static final String APPKEY = "5431d5045ccdc6b1";// 你的appkey
    public static final String URL = "https://api.binstd.com/gold/shgold";

    private GoldESDao goldESDao;

    public GoldUtils(GoldESDao goldESDao){
        this.goldESDao = goldESDao;
    }

    /**
     * 从接口出获取黄金信息
     * @return
     * @throws URISyntaxException
     */
    public List<Gold> queryGoldsFromNet() throws URISyntaxException {
        String url = URL + "?appkey=" + APPKEY;
        String result = HttpUtil.doGet(url);
        JSONObject object = JSONObject.parseObject(result);
        //获取黄金数据
        List list = JSONObject.parseObject(object.getString("result"), List.class);
        if (list == null){
            throw new RuntimeException();
        }
        //定义list存储黄金数据
        List<Gold> golds = new ArrayList<>();
        for (Object o : list) {
            Gold gold = JSON.parseObject(o.toString(), Gold.class);
            golds.add(gold);
        }
        return golds;
    }

    /**
     * 刷新elasticsearch中golds信息
     * @throws URISyntaxException
     * @return
     */
    public List<Gold> saveGolds(List<Gold> golds) throws URISyntaxException {
        if (golds.size() < 1){
            return golds;
        }
        goldESDao.deleteAll();
        goldESDao.saveAll(golds);
        return golds;
    }

    public GoldMysql goldToGoldMysql(Gold gold){
        GoldMysql mysql = new GoldMysql();
        mysql.setType(gold.getType());
        mysql.setTypename(gold.getTypename());
        mysql.setChangepercent(gold.getChangepercent());
        mysql.setTradeamount(gold.getTradeamount());
        mysql.setLastclosingprice(gold.getLastclosingprice());
        mysql.setMaxprice(gold.getMaxprice());
        mysql.setMinprice(gold.getMinprice());
        mysql.setOpeningprice(gold.getOpeningprice());
        mysql.setPrice(gold.getPrice());
        mysql.setUpdatetime(gold.getUpdatetime());
        return mysql;
    }
}
